package chapter05

import com.sun.xml.internal.bind.v2.schemagen.xmlschema.Union

import scala.math.Ordering

/**
 *
 * @author cdhuangchao3
 * @date 2023/6/8 9:40 PM
 */
object Test12_MyWhile {

  def main(args: Array[String]): Unit = {
    // 2.用闭包实现一个函数，将代码块作为参数传入，递归调用
    def myWhile(condition: => Boolean): (=> Unit) => Unit = {
      // 内存函数需要递归调用，参数是循环体
      def doLoop(op: => Unit): Unit = {
        if (condition) {
          op
          myWhile(condition)(op)
        }
      }

      doLoop _
    }

    var n = 10
    myWhile(n >= 1) {
      println(n)
      n -= 1
    }
    println("=" * 20)

    // 3.用匿名函数
    def myWhile2(condition: => Boolean): (=> Unit) => Unit = {
      // 内存函数需要递归调用，参数是循环体
      op => {
        if (condition) {
          op
          myWhile2(condition)(op)
        }
      }
    }

    n = 10
    myWhile2(n >= 1) {
      println(n)
      n -= 1
    }
    println("=" * 20)

    // 4.用柯里化
    def myWhile3(condition: => Boolean)(op: => Unit): Unit = {
      // 内存函数需要递归调用，参数是循环体
      if (condition) {
        op
        myWhile3(condition)(op)
      }
    }

    n = 10
    myWhile3(n >= 1) {
      println(n)
      n -= 1
    }
  }
}
